
import scene from '../frame/scene';

class Save {
	/**
	 * @param {string} name 存档名, archiveName
	 */
	constructor(name) {
    this.series = scene.getCurrentSeriesName();
    this.name = name;
    this.id = '';
	}

  /**
   * @returns {Promise<string>} 输出的是 asset ID
   */
	createArchive() {
		return fetch(`/aurora/asset/save/create?series=${this.series}&name=${encodeURI(this.name)}`)
			.then(d => d.json())
			.then(d => {
        if (!d.result) {
          throw { msg: '创建存档失败', data: d };
        }
        return this.id = d.data.id;
			});
	}

  /**
   * @returns {Promise<any>}
   */
	writeText(text) {
    return this.findIdOrThrow().then(id => fetch(
      `/aurora/asset/save/write/${id}`,
      { method : 'put', body: text }));
  }

  /**
   * @returns {Promise<any>} 输出的文本
   */
  writeJson(obj) {
    return this.writeText(JSON.stringify(obj));
  }

  /**
   * @returns {Promise<string>} 输出的文本
   */
  readText() {
    return this.findIdOrThrow()
      .then(id => fetch(`/aurora/asset/save/read/${id}`))
      .then(d => d.text());
  }

  /**
   * @returns {Promise<any>} 输出的文本
   */
  readJson() {
    return this.findIdOrThrow()
      .then(id => fetch(`/aurora/asset/save/read/${id}`))
      .then(d => d.json());
  }

  /**
   * @returns {Promise<string>} id, 没找到的话是 ''
   */
  findId() {
    if (this.id != '') {
      return Promise.resolve(this.id);
    }

    return fetch(`/aurora/asset/save/list/${this.series}`)
      .then(d => d.json())
      .then(d => {
        if (!d.result) {
          throw { msg: '查询存档失败', data: d };
        }
        const array = d.data.filter(item => item.name === this.name);
        this.id = array.length ? array[0].id : '';
        return this.id;
      });
  }

  /**
   * @returns {Promise<string>} id, 没找到的话是 ''
   */
  findIdOrThrow() {
    return this.findId().then(id => {
      if (id == '') {
        throw { msg: '存档不存在', data: id };
      }
      return id;
    });
  }
}

export default Save;
